package com.linsen.core.ohc.serializer;

import com.alibaba.fastjson2.JSON;
import org.caffinitas.ohc.CacheSerializer;

import java.nio.ByteBuffer;

/**
 * @author zhaoyong
 * @date 2023/3/30
 */
public class FastJsonCacheSerializer implements CacheSerializer<Object> {
    public final static FastJsonCacheSerializer INSTANCE = new FastJsonCacheSerializer();


    @Override
    public void serialize(Object o, ByteBuffer byteBuffer) {
        byteBuffer.put(JSON.toJSONBytes(o));
    }

    @Override
    public Object deserialize(ByteBuffer byteBuffer) {
        byte[] bytes = new byte[byteBuffer.capacity()];
        byteBuffer.get(bytes, 0, bytes.length);
        return JSON.parse(bytes);
    }

    @Override
    public int serializedSize(Object o) {
        return JSON.toJSONBytes(o).length;
    }
}